package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author: chenyu
 * @date: 2020/8/3 10:20
 */
@Component
@Slf4j
public class MailUtil {

    /**
     * 邮箱通知的开关
     */
    @Value("${mail.enable}")
    private Boolean enable;


    @Autowired
    private JavaMailSender mailSender;

    /**
     * @param deliver    送件人
     * @param receiver   收件人
     * @param carbonCopy 附加的收件人 ？
     * @param subject    主题
     * @param content    内容
     */
    private void sendSimpleEmail(String deliver, String[] receiver, String[] carbonCopy, String subject, String content) {

        long startTimestamp = System.currentTimeMillis();
        log.info("Start send mail ... ");

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(deliver);
            message.setTo(receiver);
            message.setCc(carbonCopy);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("邮件发送成功,{}", System.currentTimeMillis() - startTimestamp);
        } catch (MailException e) {
            log.error("邮件发送失败,{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @param title 主题
     * @param msg   内容
     */
    @Async
    public void sendMail(String title, String msg) {
        if (enable) {
            sendSimpleEmail("863234009@qq.com", new String[]{"863234009@qq.com", "1356250354@qq.com"}, null, "(正式环境)" + title, msg);
        }
    }
}

